package com.example.indenture.util;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

public class VerificationCodeGenerator {
    private static final int CODE_LENGTH = 4; // 验证码长度
    private static final int MAX_ATTEMPTS = 100; // 最大尝试次数，用于避免无限循环

    private static Set<String> usedCodes = new HashSet<>();
    private static Random random = new Random();

    public static Integer generateCode() {
        int attempts = 0;

        while (attempts < MAX_ATTEMPTS) {
            long seed = System.currentTimeMillis(); // 基于时间戳生成种子值
            random.setSeed(seed);

            StringBuilder codeBuilder = new StringBuilder();

            // 生成4位验证码
            for (int i = 0; i < CODE_LENGTH; i++) {
                int digit = random.nextInt(10); // 生成0-9的随机数字
                codeBuilder.append(digit);
            }

            String code = codeBuilder.toString();

            // 检查验证码是否已被使用
            if (!usedCodes.contains(code)) {
                usedCodes.add(code);
                return Integer.valueOf(code);
            }

            attempts++;
        }

        // 达到最大尝试次数仍未找到不重复的验证码
        throw new IllegalStateException("Unable to generate a unique verification code.");
    }
}
